<template>
  <view class="form-container">
    <uni-forms ref="form" :model="formData" :rules="rules" :show-message="false">
      <view class="form-card">
        <view class="card-title">
          <uni-icons type="bars" size="18" color="#409eff"></uni-icons>
          <text>菜单信息</text>
        </view>

        <view class="form-group">
          <view class="form-label required">上级菜单</view>
          <uni-forms-item name="parentId">
            <picker @change="handleParentChange" :value="parentIndex" :range="parentOptions" range-key="menuName" :disabled="isView">
              <view class="picker-box">
                <text>{{ parentOptions[parentIndex].menuName }}</text>
                <uni-icons type="bottom" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label required">菜单类型</view>
          <uni-forms-item name="menuType">
            <picker @change="handleMenuTypeChange" :value="menuTypeIndex" :range="menuTypeOptions" range-key="text" :disabled="isView">
              <view class="picker-box">
                <text>{{ menuTypeOptions[menuTypeIndex].text }}</text>
                <uni-icons type="bottom" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label required">菜单名称</view>
          <uni-forms-item name="menuName">
            <uni-easyinput v-model="formData.menuName" placeholder="请输入菜单名称" :disabled="isView" />
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label required">显示排序</view>
          <uni-forms-item name="orderNum">
            <uni-easyinput v-model="formData.orderNum" type="number" placeholder="请输入显示排序" :disabled="isView" />
          </uni-forms-item>
        </view>

        <view class="form-group" v-if="formData.menuType !== 'F'">
          <view class="form-label">路由地址</view>
          <uni-forms-item name="path">
            <uni-easyinput v-model="formData.path" placeholder="请输入路由地址" :disabled="isView" />
          </uni-forms-item>
        </view>

        <view class="form-group" v-if="formData.menuType === 'C'">
          <view class="form-label">组件路径</view>
          <uni-forms-item name="component">
            <uni-easyinput v-model="formData.component" placeholder="请输入组件路径" :disabled="isView" />
          </uni-forms-item>
        </view>

        <view class="form-group" v-if="formData.menuType !== 'F'">
          <view class="form-label">菜单图标</view>
          <uni-forms-item name="icon">
            <uni-easyinput v-model="formData.icon" placeholder="请输入菜单图标" :disabled="isView" />
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label">显示状态</view>
          <uni-forms-item name="visible">
            <picker @change="handleVisibleChange" :value="visibleIndex" :range="visibleOptions" range-key="text" :disabled="isView">
              <view class="picker-box">
                <text>{{ visibleOptions[visibleIndex].text }}</text>
                <uni-icons type="bottom" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label">菜单状态</view>
          <uni-forms-item name="status">
            <picker @change="handleStatusChange" :value="statusIndex" :range="statusOptions" range-key="text" :disabled="isView">
              <view class="picker-box">
                <text>{{ statusOptions[statusIndex].text }}</text>
                <uni-icons type="bottom" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label">是否缓存</view>
          <uni-forms-item name="isCache">
            <picker @change="handleCacheChange" :value="cacheIndex" :range="cacheOptions" range-key="text" :disabled="isView">
              <view class="picker-box">
                <text>{{ cacheOptions[cacheIndex].text }}</text>
                <uni-icons type="bottom" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </uni-forms-item>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="form-actions" v-if="!isView">
        <button class="submit-btn" type="primary" @click="submitForm">确 定</button>
        <button class="cancel-btn" @click="cancel">取 消</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { addMenu, updateMenu, getMenu, listMenu } from '@/api/system/menu'

export default {
  data() {
    return {
      formData: {
        menuId: '',
        parentId: 0,
        menuName: '',
        orderNum: 0,
        path: '',
        component: '',
        isFrame: '1',
        isCache: '0',
        menuType: 'M',
        visible: '0',
        status: '0',
        icon: '',
        remark: ''
      },
      rules: {
        menuName: {
          rules: [{ required: true, errorMessage: '请输入菜单名称' }]
        },
        orderNum: {
          rules: [{ required: true, errorMessage: '请输入显示排序' }]
        },
        menuType: {
          rules: [{ required: true, errorMessage: '请选择菜单类型' }]
        }
      },
      menuTypeOptions: [
        { text: '目录', value: 'M' },
        { text: '菜单', value: 'C' },
        { text: '按钮', value: 'F' }
      ],
      statusOptions: [
        { text: '正常', value: '0' },
        { text: '停用', value: '1' }
      ],
      visibleOptions: [
        { text: '显示', value: '0' },
        { text: '隐藏', value: '1' }
      ],
      cacheOptions: [
        { text: '缓存', value: '0' },
        { text: '不缓存', value: '1' }
      ],
      parentOptions: [{ menuId: 0, menuName: '主目录' }],
      menuTypeIndex: 0,
      statusIndex: 0,
      visibleIndex: 0,
      cacheIndex: 0,
      parentIndex: 0,
      title: '',
      isView: false
    }
  },
  async onLoad(options) {
    // 获取上级菜单选项
    await this.getParentMenus()

    if (options.type === 'view') {
      this.isView = true
      this.title = '查看菜单'
    }
    if (options.menuId) {
      if (!this.isView) {
        this.title = '修改菜单'
      }
      this.formData.menuId = options.menuId.toString()
      this.getDetail()
    } else {
      this.title = '新增菜单'
      // 如果有父级菜单ID，设置父级ID
      if (options.parentId) {
        this.formData.parentId = options.parentId.toString()
        this.setParentIndex(options.parentId)
      }
    }
    uni.setNavigationBarTitle({
      title: this.title
    })
  },
  methods: {
    // 获取上级菜单选项
    async getParentMenus() {
      try {
        const res = await listMenu()
        if (res.code === 200) {
          // 初始化父菜单选项
          this.parentOptions = [{ menuId: 0, menuName: '主目录' }]
          if (res.data && res.data.length > 0) {
            // 只添加目录和菜单类型作为父级选项，且不能选择自己作为父级
            const validMenus = res.data.filter(item =>
              item.menuType !== 'F' &&
              item.menuId.toString() !== this.formData.menuId
            )
            this.parentOptions.push(...validMenus)
          }
        }
      } catch (error) {
      }
    },

    // 设置父级菜单索引
    setParentIndex(parentId) {
      const index = this.parentOptions.findIndex(item => item.menuId.toString() === parentId.toString())
      this.parentIndex = index > -1 ? index : 0
    },

    // 获取菜单详情
    async getDetail() {
      try {
        const res = await getMenu(this.formData.menuId)
        if (res.code === 200) {
          Object.assign(this.formData, res.data)
          // 设置各选择器的索引
          this.menuTypeIndex = this.menuTypeOptions.findIndex(item => item.value === res.data.menuType)
          this.statusIndex = this.statusOptions.findIndex(item => item.value === res.data.status)
          this.visibleIndex = this.visibleOptions.findIndex(item => item.value === res.data.visible)
          this.cacheIndex = this.cacheOptions.findIndex(item => item.value === res.data.isCache)
          // 设置父级菜单索引
          this.setParentIndex(res.data.parentId)
        }
      } catch (error) {
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate().then(async () => {
        try {
          const submitMethod = this.formData.menuId ? updateMenu : addMenu
          const result = await submitMethod(this.formData)

          if (result.code === 200) {
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]

            if (prevPage && prevPage.$vm) {
              prevPage.$vm.getList()
            }

            uni.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 1000
            })

            setTimeout(() => {
              uni.navigateBack()
            }, 1000)
          }
        } catch (error) {
        }
      }).catch(errors => {
        const firstError = Object.values(errors)[0]?.errorMessage
        if (firstError) {
          uni.showToast({
            title: firstError,
            icon: 'none'
          })
        }
      })
    },

    // 父级菜单改变
    handleParentChange(e) {
      this.parentIndex = e.detail.value
      this.formData.parentId = this.parentOptions[this.parentIndex].menuId
    },

    // 菜单类型改变
    handleMenuTypeChange(e) {
      this.menuTypeIndex = e.detail.value
      this.formData.menuType = this.menuTypeOptions[this.menuTypeIndex].value
    },

    // 状态改变
    handleStatusChange(e) {
      this.statusIndex = e.detail.value
      this.formData.status = this.statusOptions[this.statusIndex].value
    },

    // 显示状态改变
    handleVisibleChange(e) {
      this.visibleIndex = e.detail.value
      this.formData.visible = this.visibleOptions[this.visibleIndex].value
    },

    // 缓存状态改变
    handleCacheChange(e) {
      this.cacheIndex = e.detail.value
      this.formData.isCache = this.cacheOptions[this.cacheIndex].value
    },

    // 取消
    cancel() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss">
.form-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;

  .form-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);

    .card-title {
      display: flex;
      align-items: center;
      margin-bottom: 36rpx;
      padding-bottom: 24rpx;
      border-bottom: 2rpx solid #f0f0f0;

      text {
        font-size: 32rpx;
        font-weight: 600;
        color: #2c3e50;
        margin-left: 16rpx;
      }
    }

    .form-group {
      margin-bottom: 32rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .form-label {
        font-size: 28rpx;
        color: #606266;
        margin-bottom: 16rpx;
        font-weight: 500;

        &.required::before {
          content: '*';
          color: #f56c6c;
          margin-right: 8rpx;
        }
      }

      :deep(.uni-forms-item) {
        margin: 0;
        padding: 0;

        .uni-forms-item__content {
          .uni-easyinput__content {
            background-color: #f8f9fa;
            border-radius: 12rpx;
            height: 88rpx;
            padding: 0 28rpx;

            &.is-disabled {
              background-color: #f5f7fa;

              input {
                color: #909399;
              }
            }

            input {
              font-size: 28rpx;
              color: #2c3e50;

              &::placeholder {
                color: #909399;
              }
            }
          }
        }
      }

      .picker-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background-color: #f8f9fa;
        border-radius: 12rpx;
        height: 88rpx;
        padding: 0 28rpx;
        font-size: 28rpx;
        color: #2c3e50;

        &.disabled {
          background-color: #f5f7fa;
          color: #909399;
        }
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 32rpx;
    margin-top: 48rpx;

    button {
      width: 240rpx;
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      border-radius: 44rpx;

      &.submit-btn {
        background-color: #409eff;
        color: #fff;
      }

      &.cancel-btn {
        background-color: #f5f7fa;
        color: #909399;
        border: 2rpx solid #dcdfe6;
      }
    }
  }
}
</style>